self.addEventListener('install', function (event) {
    event.waitUntil(
        console.log("servicework安装成功")
    );
})
console.log(self)

let proxyOrgin = self.location.origin;
let realOrgin;

const filterRequest = ['install.js', '']

addEventListener('fetch', e => {
    e.respondWith(fetchHandler(e));
})


function makeHtmlRes(body, type, status = 200) {
    return new Response(body, {
        status,
        headers: {
            'content-type': type,
        }
    })
}

/**
 * 网页中的请求有两种路径写法
 *  1.绝对路径  这种请求可以直接重定向
 *  2.相对路径  这种写法的请求，url中内容开头都会是以proxyOrgin，所有需要还原源地址
 *
 *
 *
 * */
async function fetchHandler(e) {
    console.log(e)
    let res;
    let request = e.request;
    if (e.request.url.endsWith('needHook=1')) {
        realOrgin = e.request.url.split('?url=')[1].split('&')[0];
        realOrgin = decodeURIComponent(realOrgin)
        if (realOrgin.endsWith('/')) {
            realOrgin = realOrgin.substr(0, realOrgin.length - 1)
        }
        console.log('实际网址为:' + realOrgin)

        res = await fetch(e.request.url);
        return res;
    }

    //现在proxyOrgin = http://localhost:8888 ,相对路径时才可能匹配到开头是proxyOrgin，
    if (request.url.startsWith(proxyOrgin)) {
        let url = reWriteUrl(request.url);
        console.log("新的url:" + url)
        const res = await fetch(url);
        //console.log(res)
        let r = makeHtmlRes(res.body, res.headers.get("content-type"));
        //console.log(r)
        return r;
    }

    let realUrl = encodeURIComponent(request.url);
    const proxyUrl = proxyOrgin + `/redirect?url=${realUrl}`;
    let res2 = await fetch(proxyUrl);
    let r = makeHtmlRes(res2.body, res2.headers.get("content-type"));
    return r;
    //console.log('放行的url：' + request.url)
    //console.log(e)

}

function reWriteUrl(url) {

    let urlObject = new URL(url);
    let realUrl = realOrgin + urlObject.pathname + urlObject.search;
    realUrl = encodeURIComponent(realUrl);
    const proxyUrl = proxyOrgin + `/redirect?url=${realUrl}`;
    return proxyUrl;

}

function printFetch(e) {
    if (!e.request.url.startsWith("chrome-extension")) {
        console.log(e)
    }
}

self.addEventListener('message', function (event) {
    console.log("SW Received Message: " + event.data);
    realOrgin = new URL(event.data)
});


function test(request) {
    let b = request.url.indexOf('vue.js') > -1;
    if (b) {
        let r = new Response('console.log("vue.js")', {
            headers: {'Content-Type': 'application/javascript; charset=utf-8'}
        })
        e.respondWith(r);
    }
}
